<?php

/**
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function kommunity_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>';
  }
}

/**
 * Allow themable wrapping of all comments.
 */
function kommunity_comment_wrapper($content, $node) {
  if (!$content || $node->type == 'forum') {
    return '<div id="comments">'. $content .'</div>';
  }
  else {
    print_r($comment);
    return '<div id="comments"><h2 class="comments">'. t('Comments') .'</h2>'. $content .'</div>';
  }
}

/**
 * Override or insert PHPTemplate variables into the templates.
 */
function kommunity_preprocess_page(&$vars) {

  $vars['tabs2']                   = menu_secondary_local_tasks();
  $vars['ie_styles6']              = kommunity_get_ie_styles6();
  $vars['ie_styles7']              = kommunity_get_ie_styles7();
  $vars['ie_pngfix_styles']        = kommunity_get_ie_pngfix_styles();
  $vars['primary_nav']             = isset($vars['primary_links']) ? theme('links', $vars['primary_links'], array('class' => 'links primary-links')) : FALSE;
  $vars['secondary_nav']           = isset($vars['secondary_links']) ? theme('links', $vars['secondary_links'], array('class' => 'links secondary-links')) : FALSE;
  $vars['left']                    = kommunity_check_left($vars['left']);

  // SEO optimization, add in the node's teaser, or if on the homepage, the mission statement
  // as a description of the page that appears in search engines
  if ($vars['is_front'] && $vars['mission'] != '') {
    $vars['meta'] .= '<meta name="description" content="'. kommunity_trim_text($vars['mission'],150) .'" />'. "\n";
  }
  else if ($vars['node']->teaser != '') {
    $vars['meta'] .= '<meta name="description" content="'. kommunity_trim_text($vars['node']->teaser,150) .'" />'. "\n";
  }
  else{
    $vars['meta'] .= '<meta name="description" content="'. kommunity_trim_text($vars['node']->body,150) .'" />'. "\n";  
  }
  // SEO optimization, if the node has tags, use these as keywords for the page
  if ($vars['node']->taxonomy) {
    $keywords = array();
    foreach($vars['node']->taxonomy as $term) {
      $keywords[] = $term->name;
    }
    $vars['meta'] .= '<meta name="keywords" content="'. implode(',', $keywords) .'" />'. "\n";
  }
  
  // DO NOT TOUCH THE FOLLOWING LINES (OF THE IF-CLAUSE) AS THEY ARE NECESSARY FOR CUSTOM THEME SETTINGS TO WORK
  if ((arg(0) == 'admin') && (arg(1) == 'build') && (arg(2) == 'themes') && (arg(3) == 'settings') && (arg(4) == 'kommunity'))
  {
  set_custom_theme_settings($vars);
  }
  
  drupal_add_css($vars['directory'] . '/layout.css', 'theme', 'all');
  
  if (theme_get_setting('kommunity_border') == 0) {
    drupal_add_css($vars['directory'] . '/thin.css', 'theme', 'all');
  }
  else {
    drupal_add_css($vars['directory'] . '/thick.css', 'theme', 'all');
  }
  
  drupal_add_js($vars['directory'] . '/images/text/text.js');

  $vars['css'] = drupal_add_css();
  $vars['styles'] = drupal_get_css();
  $vars['scripts'] = drupal_get_js();

  // Prepare header
  $site_fields = array();
  if (!empty($vars['site_name'])) {
    $site_fields[] = check_plain($vars['site_name']);
  }
  $vars['site_title'] = implode(' ', $site_fields);
  if (!empty($site_fields)) {
    $site_fields[0] = $site_fields[0];
  }
  $vars['site_html'] = implode(' ', $site_fields);
  
  // Hook into color.module
  if (module_exists('color')) {
    _color_page_alter($vars);
  }
}

/**
 * Intercept comment template variables
 *
 * @param $vars
 *   A sequential array of variables passed to the theme function.
*/

function phptemplate_preprocess_comment(&$vars){
  // if the author of the node comments as well, highlight that comment
  $node = node_load($vars['comment']->nid);
  if (($vars['comment']->uid == $node->uid) && (theme_get_setting('kommunity_comment_author') == 1)) {
    $vars['author_comment'] = TRUE;
   }
  // only show links for users that can administer links
  if (!user_access('administer comments')) {
    $vars['links'] = '';
  }
  // if subjects in comments are turned off, don't show the title then
  if (!variable_get('comment_subject_field', 1)) {
    $vars['title'] = '';
  }
  // if user has no picture, add in a filler
  if ($vars['picture'] == '') {
    $vars['picture'] = '<div class="no-picture">&nbsp;</div>';
  }
}

/*
  * Makes forums look better and is great for performance
  * More: http://www.sysarchitects.com/node/70
  * @TODO: not sure this is working yet in D6
  */
function phptemplate_preprocess_forum_topic_navigation(&$variables) {
   return '';
}


/**
 * Returns the rendered local tasks. The default implementation renders
 * them as tabs. Overridden to split the secondary tasks.
 *
 * @ingroup themeable
 */
function kommunity_menu_local_tasks() {
  return menu_primary_local_tasks();
}

function kommunity_comment_submitted($comment) {
  return t('!datetime — !username',
    array(
      '!username' => theme('username', $comment),
      '!datetime' => format_date($comment->timestamp)
    ));
}

function kommunity_node_submitted($node) {
  return t('!datetime — !username',
    array(
      '!username' => theme('username', $node),
      '!datetime' => format_date($node->created),
    ));
}

/**
 * Generates IE6 CSS links for LTR and RTL languages.
 */
function kommunity_get_ie_styles6() {
  global $language;

  $ie_css = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie6.css" />';
  if (defined('LANGUAGE_RTL') && $language->direction == LANGUAGE_RTL) {
    $ie_css .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
  }

  return $ie_css;
}

/**
 * Generates IE7 CSS links for LTR and RTL languages.
 */
function kommunity_get_ie_styles7() {
  global $language;

  $ie_css = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie7.css" />';
  if (defined('LANGUAGE_RTL') && $language->direction == LANGUAGE_RTL) {
    $ie_css .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
  }

  return $ie_css;
}

/**
 * Generates IE CSS links for LTR and RTL languages.
 */
function kommunity_get_ie_pngfix_styles() {
 
  $ie_pngfix_css = '<style type="text/css" rel="stylesheet" media="all"> img, .pngtrans { behavior: url('. base_path() . path_to_theme() .'/ie_pngfix.htc); } </style>';
  return $ie_pngfix_css;
}

/*
* Check the page width theme settings and reset to default 
* if the value is null, or invalid value is specified
*/
function kommunity_validate_page_width($page_width)
{
  global $theme_key;

  /*
  * The default values for the theme variables. Make sure $defaults exactly
  * matches the $defaults in the theme-settings.php file.
  */
  $defaults = array(             // <-- change this array
    'kommunity_page_width' => '75%',
  );

  // check if it is liquid (%) or fixed width (px)
  if(preg_match("/(\d+)\s*%/", $page_width, $match)) {
    $liquid = 1;
    $num = intval($match[0]);
    if(50 <= $num && $num <= 95) {
      return $num . "%";  // OK!
    }
  }
  else if(preg_match("/(\d+)\s*px/", $page_width, $match)) {
    $fixed = 1;
    $num = intval($match[0]);
    if(700 <= $num && $num <= 1300) {
      return $num . "px"; // OK
    }
  }
  
  // reset to default value
  variable_set(
    str_replace('/', '_', 'theme_'. $theme_key .'_settings'),
    array_merge($defaults, theme_get_settings($theme_key))
  );
  // Force refresh of Drupal internals
  theme_get_setting('', TRUE);

  return $defaults['kommunity_page_width'];
}

/*
* Check the sidebar width theme settings and reset to default 
* if the value is null, or invalid value is specified
*/
function kommunity_validate_sidebar_width($sidebar_width)
{
  global $theme_key;

  /*
  * The default values for the theme variables. Make sure $defaults exactly
  * matches the $defaults in the theme-settings.php file.
  */
  $defaults = array(             // <-- change this array
    'kommunity_sidebar_width' => '210px',
  );

  // check if it is fixed width (px)
  if(preg_match("/(\d+)\s*px/", $sidebar_width, $match)) {
    $fixed = 1;
    $num = intval($match[0]);
    if(150 <= $num && $num <= 500) {
      return $num . "px"; // OK
    }
  }
  
  // reset to default value
  variable_set(
    str_replace('/', '_', 'theme_'. $theme_key .'_settings'),
    array_merge($defaults, theme_get_settings($theme_key))
  );
  // Force refresh of Drupal internals
  theme_get_setting('', TRUE);

  return $defaults['kommunity_sidebar_width'];
}

function kommunity_check_left($left)
{
  if ($left == '') 
  {
    return '<div class="clear-block block">&nbsp;</div>';
  }
  else
  {
    return $left;
  }
}

/**
 * Trim a post to a certain number of characters, removing all HTML.
 */
function kommunity_trim_text($text, $length) {
  // remove any HTML or line breaks so these don't appear in the text
  $text = trim(str_replace(array("\n", "\r"), ' ', strip_tags($text)));
  $text = trim(substr($text, 0, $length));
  $lastchar = substr($text, -1, 1);
  // check to see if the last character in the title is a non-alphanumeric character, except for ? or !
  // if it is strip it off so you don't get strange looking titles
  if (preg_match('/[^0-9A-Za-z\!\?]/', $lastchar)) {
    $text = substr($text, 0, -1);
  }
  // ? and ! are ok to end a title with since they make sense
  if ($lastchar != '!' and $lastchar != '?') {
    $text .= '...';
  }

  return $text;
}

function set_custom_theme_settings(&$vars) {
  
  $kommunity_page_width    = kommunity_validate_page_width(theme_get_setting('kommunity_page_width'));
  $kommunity_sidebar_width = kommunity_validate_sidebar_width(theme_get_setting('kommunity_sidebar_width'));

  // Rewrite layout.css file according to theme layout settings
  $layout_css = '   #wrapper #container {
        width: ' . $kommunity_page_width . ';
      }
      body.sidebar-left #center, body.sidebar-left #footer, body.no-sidebars #center, body.sidebar-left #center {
        margin-left: -' . $kommunity_sidebar_width . ';
      }
      body.sidebar-right #center, body.sidebar-right #footer {
        margin-right: -' . $kommunity_sidebar_width . ';
      }
      body.two-sidebars #center, body.two-sidebars #footer, body.sidebar-right #center, body.two-sidebars #center {
        margin: 0 -' . $kommunity_sidebar_width . ';
      }
      body.sidebar-left #squeeze, body.no-sidebars #squeeze, body.sidebar-left #squeeze, ul.primary-links {
        margin-left: ' . $kommunity_sidebar_width . ';
      }
      body.sidebar-right #squeeze, body.sidebar-right #wrapper #container #header, body.two-sidebars #wrapper #container #header {
        margin-right: ' . $kommunity_sidebar_width . ';
      }
      body.two-sidebars #squeeze, body.sidebar-right #squeeze, body.two-sidebars #squeeze {
        margin: 0 ' . $kommunity_sidebar_width . ';
      }
      #wrapper #container .sidebar, #wrapper #container #header  #header-inner #logo-floater {
        width: ' . $kommunity_sidebar_width . ';
      }';
	  file_put_contents($vars['directory'] . '/layout.css', $layout_css);
  
    // Rewrite responsible color.inc file according to theme border settings
    $color_inc = file($vars['directory'] . '/color/color.inc');
	if (theme_get_setting('kommunity_border') == 0)
	{
	  $color_inc = str_replace('thick', 'thin', $color_inc);
	} else {
	  $color_inc = str_replace('thin', 'thick', $color_inc);
	}
	file_put_contents($vars['directory'] . '/color/color.inc', implode($color_inc));

    // Rewrite text.js file for image overlays
    $text_js = file($vars['directory'] . '/images/text/text.js');
    if (((theme_get_setting('kommunity_text_header')) == 0) && ((theme_get_setting('kommunity_text_content')) == 0) && ((theme_get_setting('kommunity_text_comment')) == 0))
    {
      $text_js[20] = 'var elements = new Array();		// Elements within this array will run SIIR
';
    }
    if (((theme_get_setting('kommunity_text_header')) == 1) && ((theme_get_setting('kommunity_text_content')) == 0) && ((theme_get_setting('kommunity_text_comment')) == 0))
    {
      $text_js[20] = 'var elements = new Array("h1","h7");		// Elements within this array will run SIIR
';
    }
	if (((theme_get_setting('kommunity_text_header')) == 0) && ((theme_get_setting('kommunity_text_content')) == 1) && ((theme_get_setting('kommunity_text_comment')) == 0))
    {
      $text_js[20] = 'var elements = new Array("h2");		// Elements within this array will run SIIR
';
    }
	if (((theme_get_setting('kommunity_text_header')) == 0) && ((theme_get_setting('kommunity_text_content')) == 0) && ((theme_get_setting('kommunity_text_comment')) == 1))
    {
      $text_js[20] = 'var elements = new Array("h3");		// Elements within this array will run SIIR
';
    }
	if (((theme_get_setting('kommunity_text_header')) == 1) && ((theme_get_setting('kommunity_text_content')) == 1) && ((theme_get_setting('kommunity_text_comment')) == 0))
    {
      $text_js[20] = 'var elements = new Array("h1","h2","h7");		// Elements within this array will run SIIR
';
    }
    if (((theme_get_setting('kommunity_text_header')) == 0) && ((theme_get_setting('kommunity_text_content')) == 1) && ((theme_get_setting('kommunity_text_comment')) == 1))
    {
      $text_js[20] = 'var elements = new Array("h2","h3");		// Elements within this array will run SIIR
';
    }
    if (((theme_get_setting('kommunity_text_header')) == 1) && ((theme_get_setting('kommunity_text_content')) == 0) && ((theme_get_setting('kommunity_text_comment')) == 1))
    {
      $text_js[20] = 'var elements = new Array("h1","h3","h7");		// Elements within this array will run SIIR
';
    }
    if (((theme_get_setting('kommunity_text_header')) == 1) && ((theme_get_setting('kommunity_text_content')) == 1) && ((theme_get_setting('kommunity_text_comment')) == 1))
    {
      $text_js[20] = 'var elements = new Array("h1","h2","h3","h7");		// Elements within this array will run SIIR
';
    }
	
    if ((theme_get_setting('kommunity_text_header') == 1) || (theme_get_setting('kommunity_text_content') == 1)) 
    {
	  global $theme_key;
      $palette = (color_get_palette($theme_key));
	  $text_js[25] = 'settings["h1"]["bgcolor"] = "' . substr($palette['top'], 1) . '";
';
      $text_js[29] = 'settings["h1"]["font_file"] = "fonts/' . theme_get_setting('kommunity_text_header_font') . '";
';
	  $text_js[39] = 'settings["h2"]["font_color"] = "' . substr($palette['link'], 1) . '";
';
	  $text_js[41] = 'settings["h2"]["font_file"] = "fonts/' . theme_get_setting('kommunity_text_content_font') . '";
';
	  $text_js[51] = 'settings["h3"]["font_color"] = "' . substr($palette['link'], 1) . '";
';
	  $text_js[53] = 'settings["h3"]["font_file"] = "fonts/' . theme_get_setting('kommunity_text_comment_font') . '";
';
	  $text_js[75] = 'settings["h7"]["font_color"] = "' . substr($palette['link'], 1) . '";
';
	  $text_js[77] = 'settings["h7"]["font_file"] = "fonts/' . theme_get_setting('kommunity_text_header_font') . '";
';
    }

    file_put_contents($vars['directory'] . '/images/text/text.js', implode($text_js));

	// END OF THE "DO NOT TOUCH" AREA

}